﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using Cell = Microsoft.Office.Interop.Word.Cell;
using System.Threading;
using System.Net;
using System.IO;
using Microsoft.VisualBasic;
using WebSocketClient;

namespace WordEdit
{
    public partial class Form1 : Form
    {
        const int TXT = 1;
        const int NET = 2;
        const int SOCKET = 3;
        Word.Application wApp;
        Word._Document wDoc;
        Object oMissing = System.Reflection.Missing.Value;
        Object oFalse = false;
        Thread childThread;
        string getUrl = "http://127.0.0.1/";
        long sleep = 3000;
        string savePath = "";
        int type = TXT;
        WSocketClient client;
        public Form1()
        {
            InitializeComponent();
        }

        private void open_Click(object sender, EventArgs e)
        {
            // Create an instance of Word  and make it visible.  
            wApp = new Word.Application();
            wApp.Visible = true;

            // Add a new document.  
            wDoc = wApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            wDoc.Select();

            this.saveclose.Enabled = true;
        }

        private void insertWord(string text)
        {
            if (wApp == null)
            {
                return;
            }
            Word.Selection wSelection;
            wSelection = wApp.Selection;
            wApp.Selection.TypeParagraph();
            wSelection.Paragraphs.OutlineLevel = Word.WdOutlineLevel.wdOutlineLevelBodyText;
            wSelection.ClearFormatting();
            wSelection.Font.ColorIndex = Word.WdColorIndex.wdBlack;
            wSelection.TypeText(text);
        }

        private void appendWord(string text)
        {
            if (wApp == null)
            {
                return;
            }
            wDoc.Paragraphs.Last.Range.Text += text;
        }

        private void save_close_Click(object sender, EventArgs e)
        {
            if (!(childThread == null))
            {
                childThread.Abort();
                childThread = null;
            }
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择保存路径";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
                savePath = dialog.SelectedPath;
            }
            else
            {
                return;
            }
            string wn = this.wordName.Text;
            if (string.IsNullOrEmpty(wn))
            {
                MessageBox.Show(this, "请输入文件名", "提示");
                return;
            }
            if (wn.EndsWith(".doc") || wn.EndsWith(".docx"))
            {
                savePath = savePath + wn;
            }
            else
            {
                savePath = savePath + wn + ".doc";
            }
            wDoc.SaveAs(savePath);
            wDoc.Close(false);
            wApp.Quit();
            wApp = null;
            System.Environment.Exit(0);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!(childThread == null))
            {
                childThread.Abort();
                childThread = null;
            }
            if (!(client == null))
            {
                // 记得释放资源否则会造成堆栈
                client.Dispose();
            }
            if (!(wApp == null))
            {
                wDoc.SaveAs("d:\\templete.doc");
                wDoc.Close(false);
                wApp.Quit();
                wApp = null;
                System.Environment.Exit(0);
            }
        }

        private string read_txt()
        {
            string txt_path = this.txtpath.Text;
            if (txt_path == null || txt_path.Length == 0)
            {
                return "未选择txt文件";
            }
            return System.IO.File.ReadAllText(txt_path, Encoding.Default);
        }

        private string getWenzi(string url)
        {
            try
            {
                if (type == NET)
                {
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                    request.Method = "GET";
                    request.Timeout = (int)sleep;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream stream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream);
                    return reader.ReadToEnd();
                }
                else
                {
                    return read_txt();
                }
            }catch(WebException wx){
                return wx.Message;
            }
        }
        private delegate void CrossThreadOperationControl();
        private void CallToChildThread()
        {
            while (true)
            {
                Thread.Sleep(3000);
                string text = getWenzi(getUrl);
                if (text.Length != 0)
                {
                        
                    // 将代理实例化为一个匿名代理
                    CrossThreadOperationControl CrossDelete = delegate()
                    {
                        string content = this.textBox1.Text;
                        if (content == null || content.Length == 0)
                        {
                            this.textBox1.Text = text;
                        }
                        else
                        {
                            this.textBox1.Text = this.textBox1.Text + "\r\n" + text;
                        }
                        appendWord(text);
                    };
                    this.textBox1.Invoke(CrossDelete);   
                }
            }
        }
        
        /// <summary>
        /// 服务端返回的消息
        /// </summary>
        private void MessageReceived()
        {
            //注册消息接收事件，接收服务端发送的数据
            client.MessageReceived += (data) =>
            {
                CrossThreadOperationControl CrossDelete = delegate ()
                {
                    string content = this.textBox1.Text;
                    if (content == null || content.Length == 0)
                    {
                        this.textBox1.Text = data;
                    }
                    else
                    {
                        this.textBox1.Text = this.textBox1.Text + "\r\n" + data;
                    }
                    appendWord(data);
                };
                this.textBox1.Invoke(CrossDelete);
            };
        }

        private void btnSendMsg()
        {
            string inputMsg = this.textBox1.Text.ToString();
            if (string.IsNullOrEmpty(inputMsg))
                MessageBox.Show("小调皮,空值不让传！");
            client.SendMessage(inputMsg);
            MessageReceived();
        }

        private void start_Click(object sender, EventArgs e)
        {
            if (type == TXT)
            {
                string txt_path = this.txtpath.Text;
                if (txt_path == null || txt_path.Length == 0)
                {
                    MessageBox.Show(this, "请选择需要读取的txt文件。", "选择txt文件!");
                    return;
                }
            }
            else
            {

                getUrl = this.reurl.Text;
                if (getUrl == null || getUrl.Length == 0)
                {
                    MessageBox.Show(this, "请填写请求地址");
                    return;
                }
            }
            if (type == SOCKET)
            {
                try
                {
                    client = new WSocketClient(getUrl);
                    if (client.Start())
                    {
                        this.textBox1.Text = this.textBox1.Text + "\r\n服务连接成功";
                        MessageReceived();
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(this, "地址错误或服务未开启", "地址错误");
                    this.textBox1.Text = this.textBox1.Text + "\r\n"+ex.Message;
                    return;
                }
            }
            else
            {
                sleep = long.Parse(this.textSleep.Text);
                ThreadStart childref = new ThreadStart(CallToChildThread);
                childThread = new Thread(childref);
                childThread.Start();
            }
            this.stop.Enabled = true;
            this.start.Enabled = false;
            this.reurl.Enabled = false;
            this.textSleep.Enabled = false;
            this.open.Enabled = false;
            this.saveclose.Enabled = false;
            this.txtbtn.Enabled = false;
            this.netbtn.Enabled = false;
        }

        private void stop_Click(object sender, EventArgs e)
        {
            if (!(childThread == null))
            {
                childThread.Abort();
                childThread = null;
            }
            if (!(client == null))
            {
                // 记得释放资源否则会造成堆栈
                client.Dispose();
                this.textBox1.Text = this.textBox1.Text + "\r\n已成功释放资源。";
                MessageReceived();
            }
            this.stop.Enabled = false;
            this.start.Enabled = true;
            this.reurl.Enabled = true;
            this.textSleep.Enabled = true;
            this.open.Enabled = true;
            this.saveclose.Enabled = true;
            this.txtbtn.Enabled = true;
            this.netbtn.Enabled = true;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            getUrl = Interaction.InputBox("请输入地址", "地址设置", "http://", -1, -1);
        }

        private void seltxt_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择txt文件";
            dialog.Filter = "图片文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                this.txtpath.Text = dialog.FileName;
            }
        }

        private void txtbtn_CheckedChanged(object sender, EventArgs e)
        {
            type = TXT;
        }

        private void netbtn_CheckedChanged(object sender, EventArgs e)
        {
            type = NET;
        }

        private void socketbtn_CheckedChanged(object sender, EventArgs e)
        {
            type = SOCKET;
        }

        private void vedioopen_Click(object sender, EventArgs e)
        {
            VedioFrom vedioFrom = new VedioFrom();
            vedioFrom.Show(this);
        }

        private void rtmpPlayer_Click(object sender, EventArgs e)
        {
            rtmpPlayer rPlayer = new rtmpPlayer();
            rPlayer.Show(this);
        }
    }
}
